var process = require('process');
var cp = require('child_process');
var iconv = require('iconv-lite');
var fs = require('fs');
var path = require('path');

module.exports = {
    exec: function (req, code, callback) {
        this.execTimeout(req, code, callback, sysConfig.responseTimeout);
    },

    execTimeout: function (req, code, callback, timeout) {
        if (code.endsWith('.py')) {
            fs.readFile(path.join(process.cwd(), code), 'utf-8', function (err, data) {
                if (err) {
                    callback && callback(err);
                    return;
                }

                getResult(req, data, callback, timeout);
            });
        } else {
            getResult(req, code, callback, timeout);
        }
    }
};

function getResult(req, code, callback, timeout) {
    var sp = cp.spawn('python', {
        encoding: 'binary',
        cwd: path.join(process.cwd(), './service/script/'),
        windowsHide: true
    });
    setTimeout(() => {
        sp.kill();
    }, timeout * 1000);
    var stdoutStr = stderrStr = '';
    sp.stdout.on('data', (data) => {
        stdoutStr += iconv.decode(data, 'cp936');
    });
    sp.stderr.on('data', (data) => {
        stderrStr += iconv.decode(data, 'cp936');
    });
    sp.stdout.on('end', () => {
        if (stderrStr == '')
            callback && callback(stdoutStr);
    });
    sp.stderr.on('end', () => {
        if (stderrStr != '')
            callback && callback(stderrStr);
    });
    code = 'query = ' + JSON.stringify(req.query) + '\r\n' +
        'form = ' + JSON.stringify(req.form) + '\r\n' +
        'session = ' + JSON.stringify(req.session.getAll()) + '\r\n' +
        'cookies = ' + JSON.stringify(req.cookies.getAll()) + '\r\n\r\n' + code;
    sp.stdin.write(code);
    sp.stdin.end();
}